package cn.js189.gateway.utils;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class ReqUtils {
	
	private ReqUtils(){
		/*empty*/
	}
	
	/**
	 * 获取body参数信息
	 * @param dataBuffer dataBuffer
	 * @param exchange exchange
	 * @param bodyParams body参数
	 * @return body参数
	 */
	public static Flux<DataBuffer> getBodyParams(String bodyParams, DataBuffer dataBuffer, ServerWebExchange exchange){
		// 取出body中的参数
		byte[] bytes = new byte[dataBuffer.readableByteCount()];
		dataBuffer.read(bytes);
		DataBufferUtils.release(dataBuffer);
		Flux<DataBuffer> cachedFlux = Flux.defer(() -> {
			DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
			DataBufferUtils.retain(buffer);
			return Mono.just(buffer);
		});
		// body参数
		bodyParams = new String(bytes, StandardCharsets.UTF_8);
		return cachedFlux;
	}
	
}
